## FocusConfig.py - Handle the config file
## Copyright (C) January 26, 2005 Erick P. Bodine
## email: erick_bodine@comcast.net
## webaddress

## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


# TODO: Validate some of the values


"""
NAME
FocusConfig.py

SYNOPSIS
import FocusConfig
try:
    properties = FocusConfig.PropertiesParser('myfocus.props')
    emailServer = properties.get('myfocus.email.server')
    
except (FocusExceptions.FatalError, IndexError), error:
    print error

DESCRIPTION
Parse the properties file.


AUTHOR
Erick P Bodine
"""

import os
import re
import logging
import fileinput
import FocusExceptions

__author__ = "$Author: ebodine $"
__date__ = "$Date: 2005-03-13 21:20:46 -0700 (Sun, 13 Mar 2005) $"
__version__ = "$Revision: 7 $"

log = logging.getLogger("myfocus")

ignore = re.compile('^#|^\s+$')
dot_split = re.compile('\.', 1)
kv_split = re.compile('=', 1)


class PropertiesParser(dict):
    """ Class for parsing the properties file. """
    def __init__(self, properties_file):
        self.properties_file = properties_file
        
        if not os.path.isfile(properties_file):
            raise FocusExceptions.FatalError, "Can't find properties file(%s)" % properties_file
        
        try:
            for line in open(properties_file).readlines():
                if ignore.search(line): continue
                key, value = [ x.strip() for x in kv_split.split(line) ]
                valid_key, valid_value = self.__validate(key, value)
                self[valid_key] = valid_value
                
        except (OSError, IOError), error:
            raise FocusExceptions.FatalError, "Problem with %s: (%s)" % (properties_file, str(error))
            
    def getSection(self, section):
        """ Retrieve the key/value pairs that only correlate to the
        passed section name.
        Params:
            section = The section name to retrieve by
        """
        dict_ = {}
        section = section.upper()
        
        for key in self.keys():
            dict_section, subsection = dot_split.split(key)
            if dict_section == section:
                dict_[key] = self.get(key)
                
        return dict_
        
    def saveNewProperty(self, property_, value):
        """ Save the new property value to the properties file
        Params:
            property_ = The property (key)
            value = The new property value
        """
        lc_property = property_.lower()
        
        for line in fileinput.input(('properties'), True, ".backup"):
            line = line.strip()
            if re.search(lc_property, line):
                line = lc_property+"="+value
            print line

    #-------------------------------------------------------#
    #                   Private Methods                     #
    #-------------------------------------------------------#
    
    def __validate(self, key, value):
        """ Validate the key &/or value property
        Params:
            key = 
            value = 
        """
        key = key.upper()
        
        email_re = re.compile('MYFOCUS\.EMAIL')
        
        if email_re.search(key):
            self.__validateEmail(key, value)
        
        return key, value
        
    def __validateEmail(self, key, value):
        pass

if __name__ == '__main__':
    
    import pprint
    
    # Setup the logging
    handler = logging.StreamHandler()
    log.setLevel(logging.DEBUG)
    format = logging.Formatter("%(asctime)s %(levelname)-3s [%(module)s:%(lineno)d] %(message)s")
    handler.setFormatter(format)
    log.addHandler(handler)
    
    module = os.path.basename(sys.argv[0])
    print "\n** Testing %s **\n" % (module+" "+ __version__+" "+__date__)
    
    # test properties files
    BAD_PROPS = os.path.normpath('test/bad.props')
    GOOD_PROPS = os.path.normpath('test/good.props')
    
    print "TEST: Parsing good props file (%s)..." % GOOD_PROPS
    Good = PropertiesParser('myfocus.props')
    pprint.pprint(Good)
    
    try:
        print "TEST: Parsing bad props file (%s)..." % BAD_PROPS
        Bad = PropertiesParser('myfocus.props')
        
    except FocusExceptions.FatalError, msg:
        print "TEST: ", msg
        
    else:
        print "FAIL: Failed to catch bad properites file"
